﻿using KnifeZ.Byeol.Models;
using KnifeZ.Byeol.Services;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;

namespace KnifeZ.Byeol.ViewModels
{
    public class TaskModifyPageViewModel : BindableBase
    {
        private bool isNew;
        public bool IsNew
        {
            get { return isNew; }
            set { SetProperty(ref isNew, value); }
        }
        private ByeolTask task;
        public ByeolTask Task
        {
            get { return task; }
            set { SetProperty(ref task, value); }
        }

        public DelegateCommand AddTaskCommand { get; set; }
        public void ModifyTask()
        {
            using var db = new DataContext(AppSettings.DefaultConnectString);
            if (!string.IsNullOrEmpty(Task.EmailAddress))
            {
                Task.IsEmail = true;
            }
            if (IsNew)
            {
                Task.TaskID = Guid.NewGuid();
                Task.CreateTime = DateTime.Now;
                Task.UpdateTime = DateTime.Now;
                db.Add(Task);
            }
            else
            {
                db.Update(Task);
            }
            db.SaveChanges();

            EventAggregatorRepository.GetInstance()
                .eventAggregator.GetEvent<PrismEventHandler<string>>()
                .Publish("RefreshTaskList");
        }

        public TaskModifyPageViewModel()
        {
            this.IsNew = true;
            Task = new ByeolTask
            {
                TaskGroupName = "Defalut",
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                IsEmail = false
            };
            this.AddTaskCommand = new DelegateCommand(new Action(ModifyTask));
        }
        public TaskModifyPageViewModel(ByeolTask byeolTask)
        {
            this.IsNew = false;
            Task = byeolTask;
            this.AddTaskCommand = new DelegateCommand(new Action(ModifyTask));
        }
    }
}
